/**
 *
 * Copyright (C) 2013 陕西威尔伯乐信息技术有限公司
 *
 * @className:com.wellbole.sms.client.impl.StatusReportFetcherImpl
 * @description: 状态报告接收器默认实现
 *
 * @version:v1.0.0
 * @author:李飞
 *
 * Modification History:
 * Date         Author      Version     Description
 * -----------------------------------------------------------------
 * 2013年7月1日      李飞                       v1.0.0        create
 *
 */
package com.wellbole.sms.client.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wellbole.sms.client.SmsClient;
import com.wellbole.sms.client.StatusReportFetcher;
import com.wellbole.sms.client.Version;
import com.wellbole.sms.client.message.StatusReportMessage;
import com.wellbole.sms.client.result.StatusReportFetchResult;

/**
 *
 * 状态报告接收器默认实现
 *
 * @author 李飞
 *
 */
public class StatusReportFetcherImpl extends AbstractOperator implements
		StatusReportFetcher {

	/**
	 * 日志
	 */
	private static final Logger logger = LogManager.getLogger(Thread
			.currentThread().getStackTrace()[2].getClassName());

	static{
		logger.info("SmsEngineClient version:"+Version.VERSION + ",update at:" + Version.LAST_UPDATE_AT);
	}

	/**
	 * 默认构造函数
	 */
	public StatusReportFetcherImpl() {
		super("1,0", "sms.statusReport");
	}

	/**
	 * 构造函数
	 *
	 * @param client
	 *            发送数据客户端
	 */
	public StatusReportFetcherImpl(SmsClient client) {
		super("1.0", "sms.statusReport", client);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.lh.sms.client.StatusReportReceiver#receive(java.lang.String)
	 */
	@SuppressWarnings("static-access")
	public StatusReportFetchResult fetch(String msgid) {

		//限制每秒最多请求20次
		try {
			Thread.currentThread().sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		// 构造参数表
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("msgid", msgid);

		// 发送请求，执行结果
		String responseStr = client.execute(this.version, this.methodName,
				parameters);

		//记录原始请求结果
		logger.debug(responseStr);

		// 根据响应内容构建发送结果
		return createResultFromResponse(responseStr);
	}

	/**
	 * 根据响应内容构建发送结果
	 *
	 * @param responseStr
	 *            执行结果
	 * @return 状态报告接收结果
	 */
	private StatusReportFetchResult createResultFromResponse(String responseStr) {
		StatusReportFetchResult result = null;
		JSONObject jsonObject = null;
		try{
			jsonObject = JSON.parseObject(responseStr);
		}catch(Exception e){
			result = StatusReportFetchResult.createSrrHasError(responseStr);
			return result;
		}
		if(jsonObject.containsKey("code")){
			result = StatusReportFetchResult.createSrrHasError(jsonObject.getString("message"));
		}else{
			int resultCode = jsonObject.getInteger("resultCode");
			if(resultCode == 2){
				result = StatusReportFetchResult.createSrrNoData();
			}else if (resultCode != 0){
				result = StatusReportFetchResult.createSrrHasError(jsonObject.getString("errorMessage"));
			}else{
				StatusReportMessage msg = new StatusReportMessage(jsonObject.getString("msgid")
																, jsonObject.getString("phone")
																, strToDate(jsonObject.getString("sendAt"))
																, strToDate(jsonObject.getString("receiveAt"))
																, jsonObject.getIntValue("smsCount")
																, jsonObject.getIntValue("statusCode")
																, jsonObject.getString("extCode"));
				result = StatusReportFetchResult.createSrrHasData(msg);
			}
		}
		return result;
	}

}
